package com.zdy.im.tio;

import java.util.Comparator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import cn.hutool.core.util.StrUtil;
/**
 * @author tanyaowu
 *
 */
public class ChannelContextComparator implements Comparator<ChannelContext> {
    @SuppressWarnings("unused")
    private static Logger log = LoggerFactory.getLogger(ChannelContextComparator.class);
    public static final ChannelContextComparator me = new ChannelContextComparator();
    /**
     * 
     */
    private ChannelContextComparator() {
    }
    /**
     * o2在前面请返回1
     * o1在前面请返回-1
     */
    @Override
    public int compare(ChannelContext o1, ChannelContext o2) {
        return compareWhenEqual(o1, o2);
    }
    /**
     * 当都为游客或为同一个用户时
     * o2在前面请返回1
     * o1在前面请返回-1
     */
    private int compareWhenEqual(ChannelContext o1, ChannelContext o2) {
        if (o2.stat.timeCreated > o1.stat.timeCreated) {//后进的在前面（2在前面 ）
            return 1;
        } else if (o2.stat.timeCreated < o1.stat.timeCreated) {//后进的在前面（1在前面 ）
            return -1;
        } else {
            String cid1 = o1.getId();
            String cid2 = o2.getId();
            int ret = StrUtil.compare(cid1, cid2, false);//cid1.compareTo(cid2);
            return ret;
        }
    }
}